import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { roleAPI, memberAPI, userAPI } from '../services/api';
import AdminPanel from './AdminPanel';
import './styles.css';

function Dashboard() {
  const navigate = useNavigate();
  const [userData, setUserData] = useState(null);
  const [userInfo, setUserInfo] = useState(null); // API获取的用户详细信息
  const [isLoadingUserInfo, setIsLoadingUserInfo] = useState(false);
  const [userRole, setUserRole] = useState(null);
  const [isLoadingRole, setIsLoadingRole] = useState(true);
  const [membershipApplyStatus, setMembershipApplyStatus] = useState(null); // null, 'applying', 'applied'
  const [isApplyingMembership, setIsApplyingMembership] = useState(false);
  const [canApplyMembership, setCanApplyMembership] = useState(true);
  const [showAdminPanel, setShowAdminPanel] = useState(false);

  useEffect(() => {
    // 从localStorage获取用户数据
    const storedUserData = localStorage.getItem('userData');
    if (storedUserData) {
      try {
        const parsedUserData = JSON.parse(storedUserData);
        setUserData(parsedUserData);
        
        // 获取用户详细信息、角色信息和会员申请状态
        if (parsedUserData && parsedUserData.userId) {
          fetchUserInfo(parsedUserData.userId);
          fetchUserRole(parsedUserData.userId);
          fetchMemberApplyStatus(parsedUserData.userId);
        }
      } catch (error) {
        console.error('解析用户数据失败', error);
      }
    }
  }, []);
  
  // 获取用户详细信息（包括头像）
  const fetchUserInfo = async (userId) => {
    try {
      setIsLoadingUserInfo(true);
      const userInfoQuery = { userId: userId };
      const response = await userAPI.getUserInfo(userInfoQuery);
      
      if (response && response.result) {
        setUserInfo(response.result);
        console.log('用户详细信息:', response.result);
      }
    } catch (error) {
      console.error('获取用户详细信息失败:', error);
    } finally {
      setIsLoadingUserInfo(false);
    }
  };
  
  // 获取用户角色
  const fetchUserRole = async (userId) => {
    try {
      setIsLoadingRole(true);
      const roleQuery = { userId: userId };
      const response = await roleAPI.getUserRole(roleQuery);
      
      if (response && response.result) {
        setUserRole(response.result.roleType);
        console.log('用户角色:', response.result.roleType);
      }
    } catch (error) {
      console.error('获取用户角色失败:', error);
    } finally {
      setIsLoadingRole(false);
    }
  };

  // 获取会员申请状态
  const fetchMemberApplyStatus = async (userId) => {
    try {
      const memberQuery = { userId: userId };
      const response = await memberAPI.getMemberApplyStatus(memberQuery);
      
      if (response) {
        const memberData = response.result;
        if (memberData.memberFlag === 0) {
          // 已申请但未审批 (member_flag = 0)
          setCanApplyMembership(false);
          setMembershipApplyStatus('applied');
        } else if (memberData.memberFlag === 1) {
          // 已经是会员 (member_flag = 1)
          setCanApplyMembership(false);
          setMembershipApplyStatus('approved');
        }
      } else {
        // 没有申请记录，可以申请
        setCanApplyMembership(true);
        setMembershipApplyStatus(null);
      }
    } catch (error) {
      console.error('获取会员申请状态失败:', error);
      // 出错时允许申请，避免阻塞正常流程
      setCanApplyMembership(true);
    }
  };

  const handleLogout = () => {
    // 清除所有登录状态
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('token');
    localStorage.removeItem('userData');
    // 跳转回登录页
    navigate('/login');
  };
  
  // 处理修改个人信息按钮点击
  const handleEditUserInfo = () => {
    // 确保有用户数据，尤其是userId
    if (userData) {
      navigate('/user-info-setup', { 
        state: { 
          userid: userData.userId,
          isEditing: true // 标记为编辑模式而非初始设置
        } 
      });
    } else {
      console.error('无法获取用户ID，无法编辑个人信息');
    }
  };

  const handleOwnAuthorPage=()=>{
    if(userData){
      navigate(`/author/${userData.userId}`);
    }
  }
  
  // 处理申请成为会员
  const handleApplyForMembership = async () => {
    if (!userData || !userData.userId) {
      console.error('无法获取用户ID');
      return;
    }
    
    if (!canApplyMembership) {
      {
        alert('您已经提交过会员申请，请等待审核');
      } 
      return;
    }
    
    try {
      setIsApplyingMembership(true);
      
      const memberData = {
        userId: userData.userId,
        memberFlag: 0, // 申请成为会员
        applyAt: new Date().toISOString()
      };
      
      const response = await memberAPI.applyForMembership(memberData);
      
      if (response && (response.code === 200 || response.success)) {
        setMembershipApplyStatus('applied');
        setCanApplyMembership(false);
        alert('会员申请已成功提交，请等待审核');
      } else {
        alert(response?.message || '申请失败，请稍后重试');
      }
    } catch (error) {
      console.error('申请会员失败:', error);
      alert('申请失败，请稍后重试');
    } finally {
      setIsApplyingMembership(false);
    }
  };

  return (
    <div className="dashboard-container">
      <header className="dashboard-header">
        <h1>
          <span 
            style={{ 
              cursor: 'pointer', 
              color: '#4a90e2', 
              transition: 'color 0.2s'
            }} 
            onClick={() => navigate('/')}
          >
            Board Demo
          </span>
          <span> - 欢迎回来{(userInfo?.nickName || userData?.result?.nickName) ? `, ${userInfo?.nickName || userData.result?.nickName}` : ''}</span>
        </h1>
        <div className="dashboard-header-buttons">
          <button className="btn-primary" onClick={handleEditUserInfo}>
            修改个人信息
          </button>
          <button className="btn-secondary" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </header>
      <div className="dashboard-content">
        <h2>用户信息</h2>
        
        {userData ? (
          <div className="user-info">
            <div className="user-avatar-section">
              <div className="dashboard-avatar">
                {isLoadingUserInfo ? (
                  <div className="dashboard-avatar-placeholder">
                    ⏳
                  </div>
                ) : userInfo?.avatar ? (
                  <img src={userInfo.avatar} alt="用户头像" />
                ) : (
                  <div className="dashboard-avatar-placeholder">
                    👤
                  </div>
                )}
              </div>
              <div className="user-details">
                <p><strong>邮箱:</strong> {userData.email || userData.result?.email}</p>
                {(userInfo?.nickName || userData.result?.nickName) && (
                  <p><strong>昵称:</strong> {userInfo?.nickName || userData.result?.nickName}</p>
                )}
                {(userInfo?.selfIntro || userData.result?.selfIntro) && (
                  <p><strong>个人简介:</strong> {userInfo?.selfIntro || userData.result?.selfIntro}</p>
                )}
              </div>
            </div>
            
            <p><strong>创建时间:</strong> {new Date(userData.createdAt || userData.result?.createTime || Date.now()).toLocaleString()}</p>
            {!isLoadingRole && userRole && (
              <p><strong>用户角色:</strong> {userRole === 'USER' ? '普通用户' : userRole}</p>
            )}
            
            <div className="dashboard-actions">
              <button className="btn-secondary" onClick={handleOwnAuthorPage}>
                个人主页
              </button>
              
              {/* 仅当用户角色为 USER 时显示申请成为会员按钮 */}
              {!isLoadingRole && userRole === 'USER' && (
                <button 
                  className={`btn-primary ${!canApplyMembership ? 'btn-disabled' : ''}`}
                  onClick={handleApplyForMembership}
                  disabled={isApplyingMembership || !canApplyMembership}
                >
                  {membershipApplyStatus === 'applied' || membershipApplyStatus === 'approved'
                    ? '申请已发送，等待审核' 
                      : isApplyingMembership 
                        ? '申请中...' 
                        : '申请成为会员'
                  }
                </button>
              )}

              {/* 仅当用户角色为 ADMIN 时显示管理员功能 */}
              {!isLoadingRole && userRole === 'ADMIN' && (
                <button 
                  className="btn-admin"
                  onClick={() => setShowAdminPanel(!showAdminPanel)}
                >
                  {showAdminPanel ? '关闭管理面板' : '打开管理面板'}
                </button>
              )}
            </div>
          </div>
        ) : (
          <p>加载用户信息中...</p>
        )}

        {/* Admin Panel */}
        {!isLoadingRole && userRole === 'ADMIN' && showAdminPanel && (
          <AdminPanel onClose={() => setShowAdminPanel(false)} />
        )}
      </div>
    </div>
  );
}

export default Dashboard;
